package com.example.skytakeoutserver.handler

import com.example.serverbase.ext.Log
import org.springframework.stereotype.Component
import org.springframework.web.reactive.socket.WebSocketHandler
import org.springframework.web.reactive.socket.WebSocketMessage
import org.springframework.web.reactive.socket.WebSocketSession
import reactor.core.publisher.Mono
import java.util.concurrent.ConcurrentHashMap


@Component
class WebSocketHandler : WebSocketHandler {

    private val sessionMap = ConcurrentHashMap<String, WebSocketSession>()

    /**
     * 重写
     */
    override fun handle(session: WebSocketSession): Mono<Void?> {
        val path = session.handshakeInfo.uri.path
        val sid = path.substringAfterLast("/")

        sessionMap[sid] = session

        val input = session.receive()
            .map(WebSocketMessage::getPayloadAsText)
            .doOnNext { msg -> Log.info("Received message from $sid:  $msg") }
            .map { msg -> session.textMessage("Received: $msg") }

        return session.send(input).then()
    }

    fun sendToAllClient(message: String) {
        sessionMap.values.forEach { session ->
            {
                try {
                    session.send(
                        Mono
                            .just(
                                session
                                    .textMessage(message)
                            )
                    ).subscribe()
                } catch (ex: Exception) {
                    Log.error("Exception occurred while sending message to $message", ex.message)
                }
            }
        }
    }
}